package com.yusys.jin.blog.serviceimpl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import com.yusys.jin.blog.controller.ex.SavePictureException;
import com.yusys.jin.blog.entity.Picture;
import com.yusys.jin.blog.entity.User;
import com.yusys.jin.blog.ex.FileIsSameWarmingException;
import com.yusys.jin.blog.ex.InsertException;
import com.yusys.jin.blog.ex.PasswordIsWrongException;
import com.yusys.jin.blog.ex.PictureNotExsitException;
import com.yusys.jin.blog.ex.UserConflictException;
import com.yusys.jin.blog.ex.UserHasExistException;
import com.yusys.jin.blog.ex.UserNotFoundException;
import com.yusys.jin.blog.mapper.UserMapper;
import com.yusys.jin.blog.service.IUserService;
import com.yusys.jin.blog.util.VerifiedCode;

@Service
public class UserServiceimpl implements IUserService {
    @Autowired
    UserMapper mapper;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override

    public void reg(User user) {
        // 先取得用户输入的用户名
        String username = user.getUserName();// custname
        String passWord = user.getPassWord();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            builder.append(VerifiedCode.getLetter());
        }
        String salt = builder.toString().trim(); // 密码因子
        System.err.println("业务层输出密码因子" + salt);
        String nickname = user.getNickName();
        String email = user.getEmail();
        // 根据用户名查询用户 验证是否已经存在
        User u = findByUsername(username);
        // 判断是否为空
        if (u != null) {
            throw new UserConflictException("用户名已被注册  请重新输入");
        }
        passWord = getMD5password(passWord, salt);// pwd
        // 准备数据库插入数据
        User data = new User();
        data.setUserName(username);
        data.setPassWord(passWord);
        data.setNickName(nickname);
        data.setSalt(salt);
        data.setEmail(email);
        System.err.println("业务层输出邮箱" + email);
        // 封装四项日志
        Date now = new Date();
        String date = sdf.format(now);
        data.setCreatedTime(date);
        data.setCreatedUser(username);
        data.setModifiedUser(username);
        data.setModifiedTime(date);
        // 执行插入
        addnewUser(data);

    }

    @Override
    public void login(User user, HttpSession session) {
        String username = user.getUserName(); // 先得到用户ID
        // 在数据库中查询是否存在该ID
        User u = findByUsername(username);
        if (u == null) {
            throw new UserNotFoundException("用户不存在");
        }
        // 如果查到了 则取出密码因子
        String salt = u.getSalt();
        // 取出用户上传的密码
        String password = user.getPassWord();
        // 对密码进行加密
        String md5Password = getMD5password(password, salt);
        // 和数据库中的密码对比
        if (!md5Password.equals(u.getPassWord())) {
            throw new PasswordIsWrongException("密码错误");
        }
        int uid = u.getUserId();
        session.setAttribute("uid", uid);

    }

    @Override
    public void checkusername(String username) {
        User u = findByUsername(username);

        if (u != null) {
            throw new UserHasExistException("用户名已被注册");
        }
    }

    /**
     * 更新用户头像
     */
    @Override
    public void updateAvatar(Picture picture, int check, MultipartFile file, File parent) {
        Date now = new Date();
        String date = sdf.format(now);
        Integer uid = picture.getUid();
        String size = picture.getSize();
        int state = picture.getState();
        List<Picture> pictureList = findPictureByUidAndSize(uid, size);
        System.err.println("用户ID为" + uid);
        User u = findByUserId(uid + "");

        if (state == 1) {
            Picture p = findUsersPicture(state, uid);
            if (p == null) {
                addPicture(picture);
                picture.setCreatedUser(u.getUserName());
                picture.setModifiedTime(date);
                picture.setCreatedTime(date);
                picture.setModifiedUser(u.getUserName());
            } else {
                if (check == 1) {
                    // 获取旧的图片存储路径
                    String OldpictureName = p.getPicturename();
                    System.out.println("old picture:   " + p);
                    String parentUrl = parent.getPath();
                    File OldFile = new File(parentUrl + OldpictureName);
                    // 如果旧的图片存在就删除
                    System.out.println("旧图片是否存在：" + OldFile.exists());
                    if (OldFile.exists()) {
                        OldFile.delete();
                    }
                    // 更新数据库资料
                    picture.setModifiedTime(date);
                    picture.setModifiedUser(u.getUserName());
                    updatePicture(picture);
                    System.err.println("更新图片数据");
                    // 存储新图片
                    try {

                        file.transferTo(new File(parent, picture.getPicturename()));
                    } catch (Exception e) {
                        throw new SavePictureException("写入图片文件失败，请联系管理员处理");
                    }
                } else {
                    throw new FileIsSameWarmingException("您已经上传过头像,再次上传会覆盖您先前上传的头像，请确认！");
                }


            }
            return;
        }
        // 根据uid查询改用户是否上传过头像

        if (u == null) {
            throw new UserNotFoundException("用户不存在请联系管理员处理");
        }
        System.err.println("检测标志：" + check);
        if (pictureList.size() >= 1 && check == 0) {
            throw new FileIsSameWarmingException("疑似重复上传，请确认是否上传");
        }
        /* if(data==null) { */

        picture.setState(0);
        picture.setCreatedUser(u.getUserName());
        picture.setModifiedTime(date);
        picture.setCreatedTime(date);
        picture.setModifiedUser(u.getUserName());
        addPicture(picture);

        /* } */
        /*
         * picture.setModifiedUser(u.getUserName());
         * picture.setModifiedTime(sdf.format(new Date()));
         * System.err.println("存在更新："+picture); updatePicture(picture);
         */

    }

    @Override
    public String findUsersAvataar(Integer state, Integer uid) {
        Picture p = findUsersPicture(state, uid);
        if (p == null) {
            throw new PictureNotExsitException();
        }
        return p.getPicturename();
    }

    private String getMD5password(String passWord, String salt) {
        String str = salt + passWord + salt;
        passWord = DigestUtils.md5DigestAsHex(str.getBytes()).toUpperCase();
        return passWord;
    }

    private User findByUsername(String username) {
        return mapper.findByUsername(username);
    }

    private void addnewUser(User data) {
        Integer rows = mapper.insert(data);
        if (rows != 1) {
            throw new InsertException("插入用户失败");
        }
    }

    private void addPicture(Picture picture) {
        Integer rows = mapper.insertAvatar(picture);
        System.err.println(rows);
        if (rows != 1) {
            throw new InsertException("插入图片路径失败");
        }
    }

    private void updatePicture(Picture picture) {
        Integer rows = mapper.updateAvatar(picture);
        if (rows != 1) {
            throw new InsertException("更新图片路径失败");
        }
    }

    private List<Picture> findPictureByUid(Integer uid) {
        return mapper.findByUid(uid);
    }

    /**
     * 判断重复上传
     *
     * @param uid
     * @param size
     * @return
     */
    private List<Picture> findPictureByUidAndSize(Integer uid, String size) {
        return mapper.findPicturesBySizeAndId(size, uid);
    }

    /**
     * 通过用户id查询用户信息
     *
     * @param id
     * @return
     */
    private User findByUserId(String id) {
        return mapper.findUserByid(id);
    }

    /**
     * 查询用户上传头像
     *
     * @param state
     * @param uid
     * @return
     */
    private Picture findUsersPicture(Integer state, Integer uid) {
        return mapper.findAvatar(state, uid);
    }

}
